package com.yitiao.producer;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQSender {

    private final RabbitTemplate rabbitTemplate;

    public RabbitMQSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setReturnCallback(new DefaultMessageCallback());
        rabbitTemplate.setConfirmCallback(new DefaultMessageCallback());
    }

    public void send(String exchange, String routingKey, Object message) {
        send(exchange, routingKey, message,new CorrelationData(IdUtil.getSnowflake().nextIdStr()));
    }

    public void send(String exchange, String routingKey, Object message, CorrelationData correlationData) {
        send(exchange, routingKey, message,correlationData,null);
    }

    public void send(String exchange, String routingKey, Object message, MessageCallback callback) {
        send(exchange,routingKey,message,new CorrelationData(IdUtil.getSnowflake().nextIdStr()),callback);
    }

    public void send(String exchange, String routingKey, Object message, CorrelationData correlationData,MessageCallback callback) {
        if (ObjectUtil.isNotNull(callback)){
            RabbitTemplate rabbitTemplate = this.setCallback(callback);
            rabbitTemplate.convertAndSend(exchange, routingKey, message,correlationData);
        }
        rabbitTemplate.convertAndSend(exchange, routingKey, message,correlationData);
    }

    private RabbitTemplate setCallback(MessageCallback callback) {
        ConnectionFactory factory = this.rabbitTemplate.getConnectionFactory();
        RabbitTemplate rabbitTemplate = new RabbitTemplate(factory);
        rabbitTemplate.setReturnCallback(callback);
        rabbitTemplate.setConfirmCallback(callback);
        return rabbitTemplate;
    }
}
